﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Configuration;
using Hxsoft.AppV1.Module;


namespace Hxsoft.AppV1._Controls
{
	public partial class InfoResourceUploader : Hxsoft.AppV1.Page
	{
		private static string _AddPhotoSubjectUrl = StringExtensions.GetEffectiveValueOrDefault(ConfigurationManager.AppSettings["AddPhotoSubjectUrl"], "/PhotoManage/ModifyPhotoSubject.aspx");
		private LoadedValue<string> loadedAddPhotoSubjectUrl;
		public string AddPhotoSubjectUrl
		{
			get {
				if (loadedAddPhotoSubjectUrl.Loader == null)
					loadedAddPhotoSubjectUrl.Loader = () => _AddPhotoSubjectUrl + "?SiteId=" + SiteId + "&Effective=true";
				return loadedAddPhotoSubjectUrl.Value;
			}
		}

		private LoadedValue<bool> loadedIsPicLibraryDetail;
		public bool IsPicLibraryDetail
		{
			get {
				if (loadedIsPicLibraryDetail.Loader == null)
					loadedIsPicLibraryDetail.Loader = () => BooleanExtensions.ParseOrDefault(StringExtensions.GetEffectiveValueOrDefault(ConfigurationManager.AppSettings["PicLibraryDetail"], "false"), false);
				return loadedIsPicLibraryDetail.Value;
			}
		}

		protected string SubmitText
		{
			get { return Res.UploadText; }
		}

		protected string TitleText
		{
			get { return Res.InfoResourceUploader_Title; }
		}

		protected string HasWatermarkText
		{
			get { return Res.InfoResourceUploader_HasWatermark; }
		}

		

		private LoadedValue<int?> loadedSiteId;
		public int? SiteId
		{
			get {
				if (loadedSiteId.Loader == null)
					loadedSiteId.Loader = () =>
						{
							var siteId=IntExtensions.ParseOrNull(Request.QueryString["SiteId"]);
							if (!siteId.HasValue)
								siteId = Sites.CurrentSiteId;
							return siteId;
						};
				return loadedSiteId.Value;
			}
		}

		private LoadedValue<Guid> loadedGlobalId;
		public Guid GlobalId
		{
			get
			{
				if (loadedGlobalId.Loader == null)
					loadedGlobalId.Loader = () => new Guid(Request.QueryString["GlobalId"]);
				return loadedGlobalId.Value;
			}
		}

		private LoadedValue<string> loadedInfoType;
		public string InfoType
		{
			get
			{
				if (loadedInfoType.Loader == null)
					loadedInfoType.Loader = () => Request.QueryString["InfoType"];
				return loadedInfoType.Value;
			}
		}

		private LoadedValue<string> loadedFilterResourceTypeName;
		public string FilterResourceTypeName
		{
			get
			{
				if (loadedFilterResourceTypeName.Loader == null)
					loadedFilterResourceTypeName.Loader = () => Request.QueryString["FilterResourceTypeName"];
				return loadedFilterResourceTypeName.Value;
			}
		}

		private LoadedValue<string> loadedClientCallbackFunction;
		public string ClientCallbackFunction
		{
			get
			{
				if (loadedClientCallbackFunction.Loader == null)
					loadedClientCallbackFunction.Loader = () => Request.QueryString["ClientCallbackFunction"];
				return loadedClientCallbackFunction.Value;
			}
		}

		protected void SetAllowUploadType(string allowUploadType)
		{
			CtrFileUploaderUploadTypeValidator.AllowUploadType = allowUploadType;
			CtrFileUploaderUploadTypeValidator.ErrorMessage = Res.ResourceUploadTypeValidateErrorMessage.Replace("{0}", allowUploadType);
		}

		protected override void OnInit(EventArgs e)
		{
			if (string.IsNullOrEmpty(FilterResourceTypeName))
				SetAllowUploadType(UploadRule.GetAllowUploadResourceType());
			else
				SetAllowUploadType(UploadRule.GetFilterResourceType(FilterResourceTypeName));

			base.OnInit(e);
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
				this.DataBind();
		}

		protected override void OnPreRender(EventArgs e)
		{
			this.RegisterHeadIncludeFile(ApplicationConfiguration.JQueryUrl, IncludeFileType.JS);
			this.RegisterHeadIncludeFile(ApplicationConfiguration.CommonScriptUrl, IncludeFileType.JS);
			this.RegisterHeadIncludeFile(ApplicationConfiguration.ResourceSelectorStyleUrl, IncludeFileType.CSS);

			CtrSubmit.Text = SubmitText;
			CtrHasWatermark.Text = HasWatermarkText;

			CtrFileUploaderUploadMaxSizeValidator.ErrorMessage = Res.ResourceUploadMaxSizeValidateErrorMessage.Replace("{0}", UploadRule.GetUploadResourceMaxSize().ToString());
			CtrRightValidator.ErrorMessage = Res.PermissionExceptionMessage;

			base.OnPreRender(e);
			PhotoSubject();
		}

		protected void BtReload_Click(object sender, EventArgs e)
		{
			PhotoSubject();
		}

		protected void CtrSubmit_Click(object sender, EventArgs e)
		{
			if (Page.IsValid)
			{
				string fileName = UploadRule.GetFileName(CtrFileUploader.FileName);
				string fileType = UploadRule.GetFileType(CtrFileUploader.FileName);

				InfoResource resource = new InfoResource();
				resource.GlobalId = GlobalId;
				resource.Name = fileName;
				resource.ResourceType = fileType;
				resource.Content = new System.Data.Linq.Binary(CtrFileUploader.FileBytes);

				InfoResourceWatermark watermark = null;
				if (CtrHasWatermark.Checked)
				{
					watermark = new InfoResourceWatermark();
					watermark.HasWatermark = CtrHasWatermark.Checked;
				}

				resource = InfoResources.Insert(resource, InfoType, watermark);

				//是否添加到相册
				if (CtrAddPicLibrary.Checked)
				{
					var subjectId = IntExtensions.ParseOrNull(CtrlPhotoSubject.SelectedValue);
					if(subjectId.HasValue)
					{
						PhotoInfo info = new PhotoInfo();
						info.PhotoName = string.Format("图片_{0}", DateTime.Now.Millisecond);
						info.PhotoImageType = string.Format("{0}.{1}", resource.ResourceId, resource.ResourceType);
						info.SubjectId = subjectId.Value;
						PhotoInfos.Insert(info);
					}
				}

				if (!string.IsNullOrEmpty(ClientCallbackFunction))
				{
					string script = @"$(function() { jQuery.pageCallback(""" + ClientCallbackFunction + @""", {""resourceId"" : """ + resource.ResourceId + @""", ""resourceType"" : """ + resource.ResourceType + @"""}); });";
					CtrCallbackScript.Text = script;
				}
			}
		}

		protected void PhotoSubject()
		{
			CtrlPhotoSubject.DataSource = Module.PhotoSubjects.GetBaseList(SiteId, null, null, null, null, null);
			CtrlPhotoSubject.DataValueField = "SubjectId";
			CtrlPhotoSubject.DataTextField = "SubjectName";
			CtrlPhotoSubject.DataBind();
			CtrlPhotoSubject.Items.Insert(0, new ListItem("--请选择--", ""));
		}

		protected void CtrFileUploaderUploadMaxSizeValidator_ServerValidate(object source, ServerValidateEventArgs args)
		{
			args.IsValid = UploadRule.IsAllowUploadResourceSize(CtrFileUploader.FileContent.Length);
		}

		protected void CtrRightValidator_ServerValidate(object source, ServerValidateEventArgs args)
		{
			args.IsValid = InfoResources.GetInsertRight(new InfoResource() {
				GlobalId = GlobalId,
			});
		}
	}
}
